<!-- 上传照片 -->
<script setup lang="ts">
import { uploadClassPhotosAPI } from '@/apis/uploadClassPhotos'
import { uploadFileAPI } from '@/apis/uploadFile'
import type { Media } from '@/components/PictureGrid.vue'
import router from '@/router'
import { useUserInfoStore } from '@/store/userInfo'

const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')

const type = ref<'image' | 'video' | null>()

// 表单数据
const formData = ref({
  medium: [] as string[],
  videoCovers: [] as string[],
})

// 是否处于加载中状态
const loading = ref(false)

onLoad(async (options) => {
  if (options && options.class_id)
    classId.value = options.class_id
  else
    uni.showToast({ title: '获取数据失败：没有班级id', icon: 'none' })
})

/* ---------------------------- ChooseImage START --------------------------- */
function handleChooseType() {
  if (!type.value) {
    uni.showActionSheet({
      itemList: ['上传照片', '上传视频'],
      success: (success) => {
        const types = ['image', 'video']
        type.value = types[success.tapIndex] as 'image' | 'video'
        handlePickImage(type.value)
      },
    })
  }
  else {
    handlePickImage(type.value)
  }
}

function handlePickImage(type: 'image' | 'video') {
  uni.showActionSheet({
    itemList: ['拍摄', '从手机相册中选择'],
    success: (result) => {
      const sourceType = result.tapIndex === 0 ? 'camera' : 'album'
      uni.chooseMedia({
        count: 9,
        mediaType: [type],
        sourceType: [sourceType],
        sizeType: ['compressed'],
        success: (result) => {
          if (result.type === 'video') {
            if (result.tempFiles.length) {
              result.tempFiles.forEach(async (path) => {
                const tempFilePath = path.tempFilePath
                const thumbTempFilePath = path.thumbTempFilePath

                const [videoUrl, videoCoverUrl] = await Promise.all([
                  uploadMedia({ tempFilePath, fileType: 'video' }),
                  uploadMedia({ tempFilePath: thumbTempFilePath, fileType: 'image' }),
                ])

                if (videoUrl)
                  formData.value.medium.push(videoUrl)
                if (videoCoverUrl)
                  formData.value.videoCovers.push(videoCoverUrl)
              })
            }
          }
          else if (result.type === 'image') {
            if (result.tempFiles.length) {
              // 遍历照片临时路径的数组，将照片上传至服务器，将返回的 url 存入 formData
              result.tempFiles.forEach(async (path) => {
                const url = await uploadMedia({ tempFilePath: path.tempFilePath, fileType: 'image' })
                if (url)
                  formData.value.medium.push(url)
                else
                  uni.showToast({ title: '上传文件发生错误', icon: 'error' })
              })
            }
            else {
              uni.showToast({ title: '没有获取到照片', icon: 'none' })
            }
          }
        },
      })
    },
  })
}

interface UploadMediaOptions {
  tempFilePath: string
  fileType: 'image' | 'video'
}

async function uploadMedia({ tempFilePath, fileType }: UploadMediaOptions) {
  const res = await uploadFileAPI({
    tempFilePath,
    fileType,
  }, userInfoStore.userInfo!.token!)

  if (res.data) {
    const resData = JSON.parse(res.data)
    if (resData.code === 1)
      return resData.data.url as string
    else
      return undefined
  }
  else {
    return undefined
  }
}

function handleDeleteMedia(media: Media) {
  formData.value.medium = formData.value.medium.filter((m, index) => index !== media.index)
}
/* ----------------------------- ChooseImage END ---------------------------- */

/**
 * @description 提交表单时触发
 */
async function handleSubmit() {
  if (formData.value.medium.length === 0) {
    uni.showToast({ title: '请至少上传一张照片或一条视频', icon: 'none' })
    return
  }

  const getParams = () => {
    if (type.value === 'image') {
      return {
        id: classId.value,
        image: formData.value.medium.join(','),
        type: '1',
        cover: formData.value.medium.join(','),
      }
    }
    else {
      return {
        id: classId.value,
        image: formData.value.medium.join(','),
        type: '2',
        cover: formData.value.videoCovers.join(','),
      }
    }
  }

  try {
    const res = await uploadClassPhotosAPI(getParams(), userInfoStore.userInfo!.token!)

    if (res.data?.code === 1) {
      router.replace({
        name: 'submitSuccess',
        params: { type: '上传照片' },
      })
    }
    else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}
</script>

<template>
  <view class="min-h-screen bg-#F8FAFE">
    <view class="bg-white px-25rpx py-48rpx">
      <PictureGrid
        mode="edit"
        :width="700"
        :cols="4"
        :medium="formData.medium.map(i => withDomain(i)!)"
        :video-covers="formData.videoCovers.map(i => withDomain(i)!)"
        @pick-image="handleChooseType"
        @delete="(media) => handleDeleteMedia(media)"
      />
    </view>
    <!-- 上传照片按钮 START -->
    <view class="fixed bottom-0 z-10 h-168rpx w-750rpx flex items-center justify-center bg-white pb-48rpx x-center">
      <button
        class="h-100rpx w-650rpx flex items-center justify-center rounded-full bg-#0037AE text-30rpx text-white font-medium leading-42rpx"
        hover-class="bg-#3266D9"
        @tap="handleSubmit"
      >
        确认上传
      </button>
    </view>
    <!-- 上传照片按钮 END -->
  </view>
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'uploadPhotos'
style:
  navigationBarTitleText: '上传相册'
layout: 'custom'
</route>
